﻿#include "explore.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDialog>
#include <QMessageBox>

#pragma execution_character_set("utf-8")

MainWindow::MainWindow(Explore* explore, QWebEngineProfile *profile, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWindow),
      m_explore(explore),
      m_profile(profile),
      m_tabWidget(new TabWidget(profile, nullptr)),
      m_statusBar(new StatusBar()),
      m_attackWaring(new AttackWaring())
{
    ui->setupUi(this);

    // 初始化应用窗口
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowTitle("safe explore(作者：不绝望的白小黑)");
    setWindowIcon(QIcon(QStringLiteral(":/safe_explore_resource/logo.png")));

    //设置tab显示网页,状态栏和进度条
    this->setLayout(new QVBoxLayout());
    QLayout *layout = ui->centeralWidget->layout();
//    layout->addWidget(m_progressBar);     // 公用一个进度条效果不好，直接去掉
    layout->addWidget(m_tabWidget);
    layout->addWidget(m_statusBar);
    m_tabWidget->createTab();

    // 监听url改变信号
    connect(m_tabWidget, &TabWidget::urlChanged, this, &MainWindow::handleUrlChanged);
    connect(ui->urlLineEditWidget, &URLLineEdit::pressUrlInputLine, this, &MainWindow::handleUrlLoad);

    // url悬停
    connect(m_tabWidget, &TabWidget::linkHovered, this, &MainWindow::handleLinkHover);

    // 不安全URL检测
    connect(m_tabWidget, &TabWidget::urlNotSafe, this, &MainWindow::handleUrlNotSafe);

    //
    connect(m_attackWaring, &AttackWaring::errorContinue, this, [=](){
        int idx = m_tabWidget->currentIndex();
        QUrl newUrl = QUrl(ui->urlLineEditWidget->urlLineInput()->text());
        WebView* webView = m_tabWidget->createTab();
        m_tabWidget->setupView(webView);
        m_tabWidget->removeTab(idx);

        qDebug() << "warning create tab url "<< newUrl.toString();
        webView->load(newUrl);
        GlobalData::instance()->set(newUrl.toString(), GlobalData::boolTrue);
    });
    TabWidget * tabWidget = m_tabWidget;
    connect(m_attackWaring, &AttackWaring::errorClose, [this]{
        m_tabWidget->removeTab(m_tabWidget->currentIndex());
    });

    // 二级菜单
    SecondMenu &menu2 = explore->secondMenu();
    menu2.setParent(this);
    menu2.updateUi();
    menu2.hide();

    QObject::connect(&explore->historyWidget(), &HistoryWidget::loadUrl, this, &MainWindow::handleUrlStringLoad);
    QObject::connect(&explore->secondMenu(), &SecondMenu::showHistoryWidget, [this, explore](){
        explore->historyWidget().show();
    });
    connect(&explore->secondMenu(), &SecondMenu::quitApplication, [this](){
         this->close();
    });

    m_messageWidget = new MessageWidget(this);
    m_messageWidget->hide();
    // 提示信息
    connect(&explore->secondMenu(), &SecondMenu::shareLink, [this](){
       m_messageWidget->showMessage("download link has been write in clipboard!");
    });

    m_feedbackWidget = new FeedBackWidget(this);
    // 反馈窗口
    connect(&explore->secondMenu(), &SecondMenu::showFeedbackDialog, [this](){
//        qDebug()<<"show feedback dialog";
        m_feedbackWidget->show();
    });
    //
    connect(m_feedbackWidget, &FeedBackWidget::showSubmitmsg, [this]() {
        m_messageWidget->showMessage("feedback have been submited");
    });

    // 设置
    m_settingWidget = new SettingWidget(this);
    m_settingWidget->updateUi();
    m_settingWidget->hide();
    connect(&explore->secondMenu(), &SecondMenu::showSettingWidget, [this](){
        m_settingWidget->show();
    });

    connect(m_settingWidget, &SettingWidget::chcaeDeleteFinidhed, [this](){
        m_messageWidget->showMessage("已成功清理应用缓存");
    });

    // 收藏夹
    m_bookMarkWidget = new BookMarkWidget();
    connect(&explore->secondMenu(), &SecondMenu::showBookMarkWidget, [this](){
        if(m_bookMarkWidget->isHidden()){
            m_bookMarkWidget->show();
        }
    });
    QObject::connect(m_bookMarkWidget, &BookMarkWidget::loadUrl, this, &MainWindow::handleUrlStringLoad);

    connect(ui->urlLineEditWidget, &URLLineEdit::markUrl, [this](){
        ui->urlLineEditWidget->urlCollectBtn()->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/collection_fill.png")));
    });
    connect(ui->urlLineEditWidget, &URLLineEdit::markUrl, m_bookMarkWidget, &BookMarkWidget::addBookMark);

    connect(m_tabWidget, &TabWidget::checkUrlIsMark, m_bookMarkWidget, &BookMarkWidget::checkCollected);
    connect(m_bookMarkWidget, &BookMarkWidget::urlCollected, this, &MainWindow::handleMarkIcon);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 处理边框拖动缩放
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = (MSG*)message;
    switch(msg->message)
        {
        case WM_NCHITTEST:
            // GET_X_LPARAM:获取的低16位，
            // GET_Y_LPARAM,获取的高16位
            // 获取鼠标点击的坐标
            // this->frameGeometry()获取的最外层边框的左上角坐标
            int xPos = GET_X_LPARAM(msg->lParam) - this->frameGeometry().x();
            int yPos = GET_Y_LPARAM(msg->lParam) - this->frameGeometry().y();
            if(xPos < boundaryWidth && yPos<boundaryWidth)                    //左上角
                *result = HTTOPLEFT;
            else if(xPos>=width()-boundaryWidth&&yPos<boundaryWidth)          //右上角
                *result = HTTOPRIGHT;
            else if(xPos<boundaryWidth&&yPos>=height()-boundaryWidth)         //左下角
                *result = HTBOTTOMLEFT;
            else if(xPos>=width()-boundaryWidth&&yPos>=height()-boundaryWidth)//右下角
                *result = HTBOTTOMRIGHT;
            else if(xPos < boundaryWidth)                                     //左边
                *result =  HTLEFT;
            else if(xPos>=width()-boundaryWidth)                              //右边
                *result = HTRIGHT;
            else if(yPos<boundaryWidth)                                       //上边
                *result = HTTOP;
            else if(yPos>=height()-boundaryWidth)                             //下边
                *result = HTBOTTOM;
            else              //其他部分不做处理，返回false，留给其他事件处理器处理
               return false;
            return true;
        }
    return false;         //此处返回false，留给其他事件处理器处理
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    // event->pos(),鼠标点击的位置，相对于接收事件的窗口坐标
    clickPoint = event->pos();
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    // 向量运算
    // pos(), QWidget, 窗口坐标，相对于父窗口，没有父窗口，也就是相对于屏幕
    this->move(event->pos() - clickPoint + pos());
}

WebView *MainWindow::currentTab()
{
    return tabWidget()->currentWebView();
}

// 最小化窗口
void MainWindow::on_minBtn_clicked()
{
    this->showMinimized();
}

// 放大或者缩小
void MainWindow::on_maxOrNormalBtn_clicked()
{
    if(this->isMaximized()){
        this->ui->maxOrNormalBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/max.png")));
        this->showNormal();
    }else{
        this->ui->maxOrNormalBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/mid.png")));
        this->showMaximized();
    }
}

void MainWindow::on_closeWindowBtn_clicked()
{
    this->close();
}

void MainWindow::handleUrlChanged(QUrl url)
{
    urlLineWidget()->urlInputUpdate(url);
    handleBackBtn();
    handleForwardBtn();
    if(url.toString().contains("https:")){
        // 根据是否是安全连接更换锁图标
        QPushButton *lockIcon = ui->urlLineEditWidget->urlHttps();
        lockIcon->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/lock2.png")));
    }else{
        QPushButton *lockIcon = ui->urlLineEditWidget->urlHttps();
        lockIcon->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/lock.png")));
    }

    m_bookMarkWidget->checkCollected(url.toString());
}


void MainWindow::handleUrlLoad(QUrl url){
    // 添加https前缀头
    QString strUrl = url.toString();
    if(strUrl.indexOf("http") == -1){
        strUrl = "https://" + strUrl;
    }
    url = QUrl(strUrl);

    m_tabWidget->currentWebView()->setUrl(url);
}

void MainWindow::handleUrlStringLoad(QString strUrl){
//    qDebug()<<"histroy: "<<strUrl;
//     添加https前缀头
    if(strUrl.indexOf("http") == -1){
        strUrl = "https://" + strUrl;
    }
    QUrl url = QUrl(strUrl);
    WebView *webView = tabWidget()->createTab();
    webView->setUrl(url);
    //    m_tabWidget->currentWebView()->setUrl(url);
}

void MainWindow::handleMarkIcon(bool s)
{
    qDebug()<<"handleMarkIcon, "<<s;
    if(s){
        ui->urlLineEditWidget->urlCollectBtn()->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/collection_fill.png")));
    }else{
        ui->urlLineEditWidget->urlCollectBtn()->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/collect.png")));
    }
}

void MainWindow::handleLinkHover(const QString url)
{
//    m_statusBar->handleShowMessage(url);
    m_statusBar->showMessage(url);
}

void MainWindow::mainWindowHandleLoadStart()
{
    ui->refreshBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/close.png")));
}

void MainWindow::mainWindowHandleLoadProgress()
{

}

void MainWindow::mainWindowHandleLoadFinish()
{
    // 开始的时候应该每个wenengine进程都有一个工具栏的。现在这样走没法弄单独终止某一个webengine进程，因为只有一个工具栏
//    ui->refreshBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/close.png")));
}

void MainWindow::on_refreshBtn_clicked()
{
//    m_statusBar->showMessage("12312");
    currentTab()->reload();
}

void MainWindow::on_backBtn_clicked()
{
    WebView *view =  currentTab();
    view->back();
    if(view->page()->history()->backItems(3).count() > 0){
        ui->backBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/back.png")));
    }else{
        ui->backBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/back2.png")));
    }
}

void MainWindow::on_forwardBtn_clicked()
{
    WebView *view =  currentTab();
    view->forward();
    if(view->page()->history()->forwardItems(3).count() > 0){
        ui->forwardBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/forward.png")));
    }else{
        ui->forwardBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/forward2.png")));
    }
}

void MainWindow::handleBackBtn(){
    WebView *view =  currentTab();
    if(view->page()->history()->backItems(3).count() > 0){
        ui->backBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/back.png")));
    }else{
        ui->backBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/back2.png")));
    }
}

void MainWindow::handleForwardBtn(){
     WebView *view =  currentTab();
    if(view->page()->history()->forwardItems(3).count() > 0){
        ui->forwardBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/forward.png")));
    }else{
        ui->forwardBtn->setIcon(QIcon(QStringLiteral(":/safe_explore_resource/forward2.png")));
    }
}

void MainWindow::on_homeBtn_clicked()
{
    currentTab()->setUrl(Explore::defaultLoadUrl);
}


void MainWindow::handleUrlNotSafe(QString url){
    qDebug()<<"handleUrlNotSafe";
    if(GlobalData::instance()->get(url) == GlobalData::boolTrue){
        return;
    }

    // 对话框方式,不使用
//    QMessageBox msgBox;
//    msgBox.setText(tr("target site maybe dangerous, Continue?"));
//    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
//    msgBox.setDefaultButton(QMessageBox::Cancel);
//    int ret = msgBox.exec();
//    if(ret == QMessageBox::Yes){
//        qDebug()<<"continue";
//        GlobalData::instance()->set(url, GlobalData::boolTrue);
//        currentTab()->setUrl(QUrl(url));
//    }
    int preIdx = m_tabWidget->currentIndex();
    m_tabWidget->addTab(m_attackWaring, tr("waring"));

    m_tabWidget->removeTab(preIdx);
}

void MainWindow::on_newTabBtn_clicked()
{
    m_tabWidget->createTab();
}

void MainWindow::on_toolBtn_clicked()
{
    qDebug()<<"show download widget";
    m_explore->downloadManagerWidget().show();
}

void MainWindow::on_menuBtn_clicked()
{
    explore()->secondMenu().updateUi();
    if(explore()->secondMenu().isHidden()){
        explore()->secondMenu().show();
    }else{
        explore()->secondMenu().hide();
    }
}

void MainWindow::on_searchPageBtn_clicked()
{
    QMessageBox msgBox;
    msgBox.setModal(true);
    msgBox.setText("该软件暂时不提供该功能");

    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
}

void MainWindow::on_paletteBtn_clicked()
{
    QMessageBox msgBox;
    msgBox.setModal(true);
    msgBox.setText("该软件暂时不提供该功能");

    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
}

void MainWindow::on_userBtn_clicked()
{
    QMessageBox msgBox;
    msgBox.setModal(true);
    msgBox.setText("该软件暂时不提供该功能");

    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
}
